#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import datetime
import sqlite3dbm
import glob
import shutil
import codecs
import re
from bs4 import BeautifulSoup

import web
from web.contrib.template import render_mako

from mako.template import Template
from mako.lookup import TemplateLookup

from sqlobject import *

from config import *
from path import *
from models import *

from paneo import *

__all__ = [
                'os',
                'sys',
                'sqlite3dbm',
                'glob',
                'shutil',
                'codecs',
                're',
                'BeautifulSoup',

                'web',
                'Template',
                'TemplateLookup',

                'IMG_CONV',

                'PANEO_ROOT',
                'PANEO_SITE_DIR',
                'PANEO_SITE_DATA_DIR',
                'PANEO_SITE_DATA_DB_DIR',
                'PANEO_CMS_PAGE_TEMPLATES_DIR',

                'ARTICLES_DB',
                'SESSION_DB',
                'PANEO_DB',

                'render',

                'dt',

                'GetHtmlMenuPages',
                'TemplateBackupWrite',

                #MODELS
                'sqlhub',
                'connectionForURI',

                'ArticlesType',
                'Articles',
                'Posts',
                'Categories',
                'Groups',

                #PANEO
                'Page',
                'PaneoPage',
                'PaneoField',

]

#render
render = render_mako(   directories=[PANEO_ROOT+'/_cms/templates/'],
                        input_encoding='utf-8',
                        output_encoding='utf-8',
                        default_filters=["none_to_blank", "unicode"],
                        encoding_errors='replace', 
                        imports=[   'from utils import none_to_blank,AWS_SEARCH_INDEX,AWS_SORT',
                                    'import web',
                                    'from config import PANEO_SITE_DIR,IMG_CONV,ARTICLES_TYPE,ARTICLES',
                                    'from models import VIEWED',])

def none_to_blank(value):
    if value is None:
        return ""
    else:
        return value 

dt = datetime.datetime.today().strftime("%Y%m%d%H")

#AMAZON PARAM
AWS_SEARCH_INDEX = {
  "All":               u"全て",
  "Apparel":           u"アパレル&ファッション雑貨",
  "Baby Product":      u"ベビー&マタニティ",
  "Book":              u"本・漫画・雑誌",
  "CE":                u"家電&カメラ",
  "DVD":               u"DVD",
  "Grocery":           u"食品&飲料",
  "Health and Beauty": u"ヘルス&ビューティー",
  "Kitchen":           u"ホーム&キッチン",
  "Music":             u"ミュージック",
  "Office Product":    u"文房具・オフィス用品",
  "Shoes":             u"シューズ",
  "Software":          u"PCソフト",
  "Sports":            u"スポーツ&アウトドア",
  "Toys":               u"おもちゃ",
  "VHS":               u"ビデオ",
  "Video Games":       u"TVゲーム",
  "Watch":             u"時計"
}

AWS_SORT = {
        "":u"-指定なし",
        "salesrank":u"総合評価",
        "price":u"価格が安い順",
        "-price":u"価格が高い順",
        "reviewrank":u"レビュー",
        "releasedate":u"発売日順",
}        

def GetHtmlMenuPages():
    n=0
    pages = {}
    file = codecs.open(PANEO_SITE_DATA_DIR+'_menu.html',"r","utf8")
    bs = BeautifulSoup(file.read(),"html5lib",fromEncoding="utf8")
    file.close()
    for a in bs.find_all("a"):
        href = a.get("href")
        id, ext = os.path.splitext(os.path.split(href)[1])
        if ext != ".html":
            id = "index"
        p = {}
        p['IDX'] = n 
        p['TYPE'] = 'MENU' 
        p['PARENT'] = ''
        if os.path.exists(PANEO_SITE_DATA_DIR+id+'.html'):
            p['TEMPLATE'] = 'OK'
        else:
            p['TEMPLATE'] = 'NG'
        p['TITLE'] = a.string 
        pages[id]=p
        n = n + 1
    return pages

def TemplateBackupWrite( tmp,html ):
    #TEMPLATEのバックアップ
    shutil.copyfile(PANEO_SITE_DATA_DIR+tmp+'.html',PANEO_SITE_DATA_DIR+'backup/'+tmp+'.html.'+dt+'.bak')
    file = codecs.open(PANEO_SITE_DATA_DIR+tmp+'.html',"w","utf8")
    file.write(html)
    file.close()

